"""
用户账户相关功能：注册、短信、登录、注销
"""
from django.db.models import F,Q
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from web.fonts.account import RegisterModelForm, SendSmsForm, LoginSMSForm, LoginForm

from web import models


def register(request):
    """注册"""
    if request.method == "GET":
        form = RegisterModelForm()
        return render(request, "register.html", {"form": form})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过，写入数据库
        form.save()
        return JsonResponse({'status': True, 'data': '/login/'})

    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """发送短信"""
    print(request.GET)  # <QueryDict: {'mobile_phone': ['asdasdsa'], 'tpl': ['register']}>
    form = SendSmsForm(request, data=request.GET)  # 将获取传入
    # 只是校验手机号：不能为空，格式正确，是否已经注册过
    if form.is_valid():
        # 发送短信
        # 写redis
        return JsonResponse({"status": True})

    return JsonResponse({"status": False, "error": form.errors})


def login_sms(request):
    """用于登陆页面"""
    if request.method == "GET":
        form = LoginSMSForm()
        return render(request, "login_sms.html", {"form": form})
    form = LoginSMSForm(request.POST)
    if form.is_valid():
        # 用户输入正确，登录成功
        mobile_phone = form.cleaned_data["mobile_phone"]

        # 把用户信息放入session
        user_object = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        request.session["user_id"] = user_object.id
        request.session["user_name"] = user_object.username
        print(user_object)
        return JsonResponse({"status": True, "data": "/index/"})  # 登录成功就返回到了index页面
    return JsonResponse({"status": False, "error": form.errors})


def login(request):
    """ 用于用户名密码登录(验证码) """
    if request.method == "GET":
        form = LoginForm(request)
        return render(request, "login.html", {"form": form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():  # from里面有数据
        username = form.cleaned_data["username"]  # 获取用户输入的内容
        password = form.cleaned_data["password"]

        # 因为我们用的是手机号和邮箱登录，所以
        # (手机=username and pwd=pwd) or (邮箱=username and pwd=pwd)  使用Q的方法
        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()

        if user_object:  # 为true的话就登录成功
            # 登录成功
            request.session["user_id"] = user_object.id # 把用户的id保存在session，然后用中间键检查是否登录，在改变basic.html的信息
            request.session.set_expiry(60*60*24*14) # 让用户保持2周

            return redirect('index')
        form.add_error('username', "用户名或密码错误")  # 登录成功就添加错误信息

    return render(request, "login.html", {"form": form})  # 没有登录成功就返回原页面


def image_code(request):
    """ 用户生成图片验证码 """
    from io import BytesIO
    from Utils.images_code import check_code
    images_object, code = check_code()

    stream = BytesIO()
    images_object.save(stream, 'png')

    request.session["image_code"] = code  # 把code放入session中
    request.session.set_expiry(60)  # 主动修改session的过期时间为60s

    return HttpResponse(stream.getvalue())  # 将图片验证码保存在内存中，在返回给页面
